<?php defined('SYSPATH') or die('No direct script access.') ;
/**
 * 管理员权限模型
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: privilege.php 1 2014-01-13 15:05:51Z zhouyl $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Model_Manager_Privilege extends Model
{

    /**
     * 获取权限列表
     *
     * @return array
     */
    public function all()
    {
        $rows = DB::select(
                'priv.priv_id', 'priv.token', 'priv.priv_name',
                'res.res_id', 'res.res_name'
            )
            ->from(array('manager_privileges', 'priv'))
            ->join(array('manager_resources', 'res'))
            ->on('priv.res_id', '=', 'res.res_id')
            ->order_by('res.res_id', 'ASC')
            ->order_by('priv.priv_id', 'ASC')
            ->fetch_all();

        $privileges = array();
        foreach ($rows as $row)
        {
            $privileges[$row['res_name']][] = $row;
        }

        return $privileges;
    }

    /**
     * 获取所有权限列表
     *
     * @return array
     */
    public function all_sql()
    {
        return DB::select('priv.*', 'res.res_name')
            ->from(array('manager_privileges', 'priv'))
            ->join(array('manager_resources', 'res'), 'INNER')
            ->on('priv.res_id', '=', 'res.res_id')
            ->order_by('res.sort_order', 'ASC');
    }

    /**
     * 获取指定权限
     *
     * @param  int  $priv_id
     * @return array
     */
    public function get($priv_id)
    {
        return DB::select()
            ->from('manager_privileges')
            ->where('priv_id', '=', $priv_id)
            ->fetch_row();
    }

    /**
     * 添加权限
     *
     * @param  array  $data
     * @return bool
     */
    public function add(array $data)
    {
        $v = $this->_validate($data);
        $this->validation($v);
        if ( ! $v->check() OR ! empty($this->_errors))
        {
            return FALSE;
        }

        $data = array (
            'res_id' => $v->res_id,
            'token' => $v->token,
            'priv_name' => $v->priv_name,
        );

        // 写入权限信息
        DB::insert('manager_privileges', $data)->execute();

        // 重新加载权限
        Manager::instance()->refresh();

        return TRUE;
    }

    /**
     * 编辑权限
     *
     * @param  int   $priv_id
     * @param  array $data
     * @return bool
     */
    public function edit($priv_id, array $data)
    {
        $privilege = $this->get($priv_id);

        if ( ! $privilege)
        {
            return $this->error('priv_id', 'not_found');
        }

        $v = $this->_validate($data);
        $this->validation($v);
        if ( ! $v->check() OR ! empty($this->_errors))
        {
            return FALSE;
        }

        $set = array (
            'res_id' => $v->res_id,
            'token' => $v->token,
            'priv_name' => $v->priv_name,
        );

        // 更新权限信息
        DB::update('manager_privileges', $set)
            ->where('priv_id', '=', $priv_id)
            ->execute();

        // 重新加载权限
        Manager::instance()->refresh();

        return TRUE;
    }

    /**
     * 数据验证
     *
     * @param  array  $data
     * @return Validation
     */
    protected function _validate(array $data)
    {
        return Validation::factory($data)
            ->rule('res_id', 'not_empty')
            ->rule('res_id', 'numeric')
            ->rule('res_id', array($this, 'resource_exists'), array(':value'))
            ->rule('token', 'not_empty')
            ->rule('token', 'regex', array(':value', '/^[a-z0-9\.\-_]{4,20}$/'))
            ->rule('priv_name', 'not_empty')
            ->rule('priv_name', 'regex', array(':value', '/^[^\'\"\:;,\<\>\?\\\*\=\+\{\}\[\]\)\(\^%\$#\!`\s]+$/'));
    }

    /**
     * 删除权限
     *
     * @param  int  $priv_id
     * @return bool
     */
    public function del($priv_id)
    {
        // 删除权限数据
        DB::delete('manager_privileges')->where('priv_id', '=', $priv_id)->execute();

        // 删除权限规则数据
        DB::delete('manager_rules')->where('priv_id', '=', $priv_id)->execute();

        // 重新加载权限
        Manager::instance()->refresh();

        return TRUE;
    }

    /**
     * 查询资源 ID 是否存在
     *
     * @param  int  $res_id
     * @return bool
     */
    public function resource_exists($res_id)
    {
        return (bool) Model::factory('manager_resource')->get($res_id);
    }
}